package com.example.config;

//import com.example.handler.SecurityAccessDeniedHandler;
//import com.example.handler.SecurityAuthenticationEntryPoint;

import com.example.security.handler.SecurityAccessDeniedHandler;
import com.example.security.handler.SecurityAuthenticationEntryPoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(jsr250Enabled = true, securedEnabled = true)
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers("/demo/abc").permitAll()
                        .requestMatchers(HttpMethod.GET, "/order").permitAll()
                        .requestMatchers(HttpMethod.GET, "/jobLauncher").permitAll()
//                        允许访问/doc.html以及所有openapi 3相关的路径
                        .requestMatchers(
                                new AntPathRequestMatcher("/favicon.ico"),
                                new AntPathRequestMatcher("/doc.html"),
                                new AntPathRequestMatcher("/v3/api-docs/**"),
                                new AntPathRequestMatcher("/webjars/**")
                        ).permitAll()
                        .requestMatchers("/demo/resourceone").hasAuthority("SCOPE_message.read") // 必须有read权限才可访问
                        .anyRequest().authenticated())
                // Form login handles the redirect to the login page from the
                // authorization server filter chain
//                .oauth2ResourceServer((resourceServer) -> resourceServer
//                        .accessDeniedHandler(new SecurityAccessDeniedHandler())
//                        .authenticationEntryPoint(new SecurityAuthenticationEntryPoint())
//                        .jwt(Customizer.withDefaults()));

                .oauth2ResourceServer((resourceServer) -> resourceServer
                        .accessDeniedHandler(new SecurityAccessDeniedHandler())
                        .authenticationEntryPoint(new SecurityAuthenticationEntryPoint())
                        .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));
        return http.build();
    }

    @Bean
    public JwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        // 设置权限前缀（默认是 SCOPE_）
        grantedAuthoritiesConverter.setAuthorityPrefix("");
        // 指定权限声明字段（默认是 scope）
        grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");

        JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
        jwtConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
        return jwtConverter;
    }
}